<?php


include_once (APPLICATION_PATH."/library/Fpdf/fpdf.php");

/**
 * Sgit_Pdf
 * 
 * @package   
 * @author sgit_development
 * @copyright juanma
 * @version 2012
 * @access public
 */
class Sgit_Pdf extends FPDF
{
   protected $_resaltar_col=array();
   protected $_resaltar_row=array();
   protected $_header=array();
   protected $_keys=array();
   protected $_widths=array();
   
   protected $A4_width=297;
   protected $A4_height=210;
    
    
    
    function __construct($orientation='P'){
        parent::FPDF($orientation);
        $this->init();
    }
    
    function init(){
        $this->SetAuthor('Telvent Global Services');
        $this->SetCreator('PHP + FPDF');
        $this->SetDisplayMode('fullpage');      
        $this->SetTopMargin(15);
        $this->SetLeftMargin(5);  
        $this->AliasNbPages(); 
        $this->AddPage();
        
        $this->translate= Zend_Registry::get('Zend_Translate');
    }
    
    
    function setColumnas($columnas)
    {        
        
        
    
        foreach($columnas as $k => $col){
            
            
            $this->_header[$k]=$this->translate->translate($col['header']);
            $this->_keys[$k]=$col['key'];
            $this->_w[$k]=$col['width'];
            
            
            
            if($col['resaltar_col']===true){
                 $this->_resaltar_col[$k]=$k;
            }
        }
        
        $this->SetWidths($this->_w);
    
    }
    
    function resaltarRows($rows)
    { 
        if($rows) $this->_resaltar_row=$rows;
    }
    
    
    
    function render($data,$file='')
    {
        if(empty($this->_widths)){
            $this->SetWidths();
        }
        
        
        $this->tableHeader();
        $this->loopRows($data);
        
        if(!$file){
            $file='file';
        }
        $this->Output($file.'.pdf','D');
        
    }
    
    
    
    
    
    function reemplazaCaracteres($value)
    {
        $value = str_replace("€", chr(128), $value);
        return $value;
    }
    
    
    
    function loopRows($data){
        
            $fill=0;
    
    		foreach($data as $id_fila => $fila) {
    			$g=array();
    			foreach($this->_keys as $key )
                {
    				$g[]=$this->reemplazaCaracteres($fila[$key]);
    			}
                
                if($this->_resaltar_row){
                    $resalta=in_array($id_fila,$this->_resaltar_row);
                }else{
                    $resalta=false;
                }
                
    		    $this->Row($g,$fill,$resalta);
    		    $fill=!$fill; 
    		}  
    }
    
    
    
    function SetWidths($width='')
    {
        //Set the array of column widths
        $f=($this->CurOrientation=='P') ? $this->A4_height-10 : $this->A4_width-10;
        
    
        if(count($width)==count($this->_header)){
            $relation=$f/array_sum($width);
            
            foreach($width as $k => $ancho_celda){
            	$ancho_modificado[$k]=round( $ancho_celda * $relation,2);
            }
            
            $this->_widths=$ancho_modificado;
            
        }else{
            
            foreach($this->_header as $k => $v){
                $ancho_modificado[$k]=round( $f/count($this->_header),2);
            }
            $this->_widths=$ancho_modificado;
        }
        return $this->_widths;
    
        
    }
    
    
    
    function SetAligns($a)
    {
        //Set the array of column alignments
        $this->aligns=$a;
    }
    
    function SetTitle($title,$title2='')
    {
        $this->title=$title;
        $this->title2=$title2;
    }
    
    function Row($data,$fill,$resalta=false)
    {
        //Calculate the height of the row
        $nb=0;
        for($i=0;$i<count($data);$i++)
            $nb=max($nb,$this->NbLines($this->_widths[$i],$data[$i]));
        $h=5*$nb;
        //Issue a page break first if needed
        $this->CheckPageBreak($h);
        //Draw the cells of the row
    
        for($i=0;$i<count($data);$i++)
        {
            
            $relleno='FD';
        	$relleno=($fill)? 'FD':'D';
            
            if(in_array($i,$this->_resaltar_col)){
                $this->SetFillColor(195,195,195);
                $relleno='FD';
            }else{
                $this->SetFillColor(215,215,215);
            }
            
            if($resalta){
                $this->SetFillColor(254,124,76);
                $relleno='FD';
            }
            
            $w=$this->_widths[$i];
            $a=isset($this->aligns[$i]) ? $this->aligns[$i] : 'L';
            //Save the current position
            $x=$this->GetX();
            $y=$this->GetY();
            //Draw the border
            $this->Rect($x,$y,$w,$h,$relleno);
            //Print the text
            $this->MultiCell($w,5,utf8_decode($data[$i]));
            //Put the position to the right of the cell
            $this->SetXY($x+$w,$y);
        }
        
        //Go to the next line
        $this->Ln($h);
        
    }
    
    
    function tableHeader()
    {
    	$data=$this->_header;
    
    	$this->SetFont('Arial','B',10);
    	$this->SetTextColor(255,255,255);
        
        if($this->CurOrientation=='P')
        {
       	    $this->Text(10,16,$this->title.'    '.$this->title2); 
        }else{
       	    $this->Text(15,22,$this->title.'    '.$this->title2); 
        }
    
    

    	$this->Ln(2);
    	
    	$this->SetFont('Arial','B',5);
    	
        $this->SetFillColor(127,136,143);
    	$this->SetTextColor(255,255,255);
    	$this->SetDrawColor(215,215,215);
        
    	$this->SetLineWidth(.4);
    	
        //Calculate the height of the row
        $nb=0;
        for($i=0;$i<count($data);$i++)
            $nb=max($nb,$this->NbLines($this->_widths[$i],utf8_decode($data[$i])));
        $h=5*$nb;
        //Issue a page break first if needed
        //Draw the cells of the row
        for($i=0;$i<count($data);$i++)
        {
            $w=$this->_widths[$i];
            $a=isset($this->aligns[$i]) ? $this->aligns[$i] : 'C';
            //Save the current position
            $x=$this->GetX();
            $y=$this->GetY();
            //Draw the border
            $this->Rect($x,$y,$w,$h,'DF');
            //Print the text
            $this->MultiCell($w,5,utf8_decode($data[$i]),0,$a);
            //Put the position to the right of the cell
            $this->SetXY($x+$w,$y);
        }
        
        
    	$this->SetFillColor(246,246,246);
    	$this->SetTextColor(61);
    	$this->SetFont('');
        $this->Ln($h);
    
    }
    
    
    
    function CheckPageBreak($h)
    {
        //If the height h would cause an overflow, add a new page immediately
        if($this->GetY()+$h>$this->PageBreakTrigger){
            $this->AddPage($this->CurOrientation);
            $this->tableHeader();
        }
            
        
    }
    
    function NbLines($w,$txt)
    {
        //Computes the number of lines a MultiCell of width w will take
        $cw=&$this->CurrentFont['cw'];
        if($w==0)
            $w=$this->w-$this->rMargin-$this->x;
        $wmax=($w-2*$this->cMargin)*1000/$this->FontSize;
        $s=str_replace("\r",'',$txt);
        $nb=strlen($s);
        if($nb>0 and $s[$nb-1]=="\n")
            $nb--;
        $sep=-1;
        $i=0;
        $j=0;
        $l=0;
        $nl=1;
        while($i<$nb)
        {
            $c=$s[$i];
            if($c=="\n")
            {
                $i++;
                $sep=-1;
                $j=$i;
                $l=0;
                $nl++;
                continue;
            }
            if($c==' ')
                $sep=$i;
            $l+=$cw[$c];
            if($l>$wmax)
            {
                if($sep==-1)
                {
                    if($i==$j)
                        $i++;
                }
                else
                    $i=$sep+1;
                $sep=-1;
                $j=$i;
                $l=0;
                $nl++;
            }
            else
                $i++;
        }
        return $nl;
	}


	function Header()
	{

	    //Logo
        if($this->CurOrientation=='P')
        {
            $img='fondopdf.png';
            $this->Image(PUBLIC_PATH.'/img/fondopdf.png',0,0,210,16.4);
            $this->Ln(4);
        }else{
            $img='fondopdf.png';
            $this->Image(PUBLIC_PATH.'/img/fondopdf2.png',0,0,297,23.3);
            $this->Ln(8);
        }


	    
	   
	}
	
	//Pie de página
	function Footer()
	{
	    //Posición: a 1,5 cm del final
	    $this->SetY(-15);
	    //$this->Cell(40,10,utf8_decode('Página') . ' '.$this->PageNo().'/{nb}',0,0,'L');
	    

		$h=($this->CurOrientation=='P') ? 277 : 192;


	    $this->SetFont('Arial','B',6);
	    $this->SetTextColor(145,145,145);
	    $this->Text(25,$h+8,$this->translate->translate(utf8_decode('Antes de imprimir este documento piense bien si es necesario hacerlo:')));
	    $this->Text(25,$h+12,$this->translate->translate(utf8_decode('El medio ambiente es cosa de todos.')));
	    $this->Image(PUBLIC_PATH.'/img/ecomail.png',10,$h);
	    
	    $this->SetFont('Arial','I',6);
	    
        
        
        $_auth = Zend_Auth::getInstance();
        $now=Zend_Date::now();
        
	    $this->Cell(0,5,$this->translate->translate(utf8_decode('Informe generado por ')).utf8_decode($_auth->getIdentity()->nombre).'  '.$now,0,1,'R');
		$this->Cell(0,5,$this->translate->translate(utf8_decode('Página')) . ' '.$this->PageNo().'/{nb}',0,0,'R');
		
	}
	
	function grafica($grafica)
	{
	   $h = ($this->CurOrientation=='P') ? 277 : 192;
       $w = ($this->CurOrientation=='P') ? 192 : 277;
       
       $y = $this->GetY()+5;
       $this->Ln(3);
       
        foreach($grafica as $v){
            $graf=$v[0];
            $width=$v[1];
            $height=$v[2];
            $marginx=($w-$width)/2;
     
     
            if($y + $height > $h){
    			$this->AddPage();
                $y=20;
    		}
		 		
    	    $this->Image('http://127.0.0.1/'.$graf,$marginx,$y,$width,$height,'PNG');

             $y =$y+$height;
        }


		

	}

}
